package com.cskaoyan.controller.backstagecontroller;

import com.cskaoyan.bean.pojo.User;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.Info;
import com.cskaoyan.bean.LoginUser;
import com.cskaoyan.bean.data.DashboardData;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.service.UserService;
import com.cskaoyan.realm.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;


@RestController
@RequestMapping("admin")
public class AuthController {

    @Autowired
    UserService userService;

    @Autowired
    AdminService adminService;

    /**
     * 需要注册adviceor
     * 登录所需要的权限？多个权限是or关系
     * @param user
     * @return
     */
    @RequestMapping("auth/login")
    public BaseRespVo login(@RequestBody LoginUser user) {

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MallToken(user.getUsername(), user.getPassword().toCharArray(), subject.getSession().getHost(), "admin"));
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("用户名或者密码错误，请重试！");
        }
        Serializable id = subject.getSession().getId();
        System.out.println("是否认证成功？" + subject.isAuthenticated());
        return BaseRespVo.ok(id.toString());
    }

    @RequestMapping("auth/info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        String username = primaryPrincipal.getUsername();
        Info info = null;
        try {
            info = adminService.selectAdminInfoByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return BaseRespVo.fail("信息获取失败！");
        }
        return BaseRespVo.ok(info);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @RequestMapping("auth/logout")
    public BaseRespVo logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    //首页
    @RequestMapping("dashboard")
    public BaseRespVo dashboard(DashboardData dashboardData) {
        DashboardData dashboardData1 = userService.selectDashboardData(dashboardData);
        return BaseRespVo.ok(dashboardData1);
    }

}
